<template>
  <div class="main">
    <h1>WebSocket Chat</h1>
    <input v-model="message" @keyup.enter="sendMessage" placeholder="Type a message..." />
    <button @click="sendMessage">Send</button> <!-- 添加发送按钮 -->
    <ul>
      <li v-for="(msg, index) in messages" :key="index">{{ msg }}</li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { Client } from '@stomp/stompjs';
import type { Message } from '@stomp/stompjs'; // 使用 IMessage 作为消息类型

const message = ref('');
const messages = ref<string[]>([]);
let stompClient: Client | null = null;
const token = localStorage.getItem('token');

const connect = () => {
  const socket = new WebSocket('ws://localhost:8080/ws');
  stompClient = new Client({
    webSocketFactory: () => socket,
    connectHeaders: {
      Authorization: `Bearer ${token}`,
    },
    debug: (str: string) => { console.log('STOMP: ' + str); },
    onConnect: () => {
      console.log('Connected to WebSocket');
      stompClient?.subscribe('/topic/messages', (frame: Message) => {
        const receivedMessage = frame.body;
        messages.value.push(receivedMessage);
      });
    },
  });
  stompClient.activate();
};


const sendMessage = () => {
  if (message.value.trim() !== '') {
    stompClient?.publish({
      destination: '/app/send',
      body: message.value,
      headers: { 'Authorization': `Bearer ${token}` },
    });
    console.log('Sent message:', message.value); // 打印发送的消息
    message.value = ''; // 清空输入框
  }
};

onMounted(() => {
  connect();
});

onBeforeUnmount(() => {
  if (stompClient) {
    stompClient.deactivate();
  }
});
</script>

<style scoped>
input {
  margin-bottom: 10px;
  width: 300px;
}
button {
  margin-left: 10px;
}
ul {
  list-style-type: none;
  padding: 0;
}
</style>
